<?php namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Type;
use App\Product;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;

class ProductController extends Controller
{
    //产品管理
    public function getIndex(Request $request)
    {
        $appends = $request->all();
        $list = Product::orderBy('created_at', 'DESC');
        if (isset($appends['type_id']) && 0 != $appends['type_id']) {
            $list = $list->where('type_id', $appends['type_id']);
        }
        if (isset($appends['name'])) {
            $list = $list->where('name', 'like', '%' . $appends['name'] . '%');
        }
        $list = $list->paginate(config('site.admin.pageSize'));
        $parents = $this->getParents();
        return view('admin.product.index', [
            'list' => $list,
            'appends' => $appends,
            'parents' => $parents,
        ]);
    }

    public function getUpdate(Request $request, $id = 0)
    {
        $model = Product::findOrNew($id);
        $parents = $this->getParents();
        return view('admin.product.update', [
            'model' => $model,
            'parents' => $parents,
        ]);
    }

    public function postUpdate(Request $request, $id = 0)
    {
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        $model = Product::findOrNew($id);
        $data = $request->all();
        $attributes = [
            'name' => '产品名称',
            'name_cn' => '中文名称',
            'type_id' => '产品类别',
        ];
        $rules = [
            'name' => 'required',
            'name_cn' => 'required',
            'type_id' => 'required',
        ];
        $messages = [
            'required' => ':attribute 不能为空.',
            'unique' => ':attribute 已经被占用.',
            'exists' => ':attribute 无此类别，或此类别已经被删除..',
        ];
        $validator = \Validator::make($data, $rules, $messages, $attributes);
        if ($validator->fails()) {
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        } else {
            if (0 == $id || 0 == $model->user_id) {
                $data['user_id'] = \Auth::user()->id;
            }
            $model->fill($data);
            $model->save();
            if ($model->id) {
                $ret = ['state' => 'success', 'message' => '操作成功'];
            } else {
                $ret['message'] = '保存出错';
            }
        }
        return \Response::json($ret);
    }

    public function anyDelete($id)
    {
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        if (Product::destroy($id)) {
            $ret = ['state' => 'success', 'message' => '删除成功'];
        }
        return \Response::json($ret);
    }

    //类别管理
    public function getType(Request $request)
    {
        $appends = $request->all();
        $list = Type::orderBy('parent_id', 'ASC');
        if (isset($appends['parent_id']) && 0 != $appends['parent_id']) {
            $list = $list->where('parent_id', $appends['parent_id']);
        }
        if (isset($appends['name'])) {
            $list = $list->where('name', 'like', '%' . $appends['name'] . '%');
        }
        $list = $list->paginate(config('site.admin.pageSize'));
        $parents = $this->getParents();
        return view('admin.product.type', [
            'list' => $list,
            'appends' => $appends,
            'parents' => $parents,
        ]);
    }

    public function getUpdatet($id = 0)
    {
        $model = Type::findOrNew($id);
        $parents = $this->getParents();
        return view('admin.product.updatet', [
            'model' => $model,
            'parents' => $parents,
        ]);
    }

    public function postUpdatet(Request $request, $id = 0)
    {
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        $model = Type::findOrNew($id);
        $data = $request->all();
        $attributes = ['name', '类别名称'];
        $ret['message'] = $data['name'];
        $attributes = [
            'name' => '标题',
        ];
        $rules = [
            'name' => 'required|unique:types,name,' . $id,
        ];
        $messages = [
            'required' => ':attribute 不能为空.',
            'unique' => ':attribute 已经被占用.',
        ];
        $validator = \Validator::make($data, $rules, $messages, $attributes);
        if ($validator->fails()) {
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        } else {
            if (0 == $id || 0 == $model->user_id) {
                $data['user_id'] = \Auth::user()->id;
            }
            $model->fill($data);
            $model->save();
            if ($model->id) {
                Cache::forget('parents');
                $ret = ['state' => 'success', 'message' => '操作成功'];
            } else {
                $ret['message'] = '保存出错';
            }
        }
        return \Response::json($ret);
    }

    public function postDeletet($id)
    {
        $ret = ['state' => 'fail', 'message' => '该类别包含子类别，或改类别含有产品，无法删除。'];
        //判断是否可以删除
        $childType = Type::where('parent_id', $id)->select('id')->first();
        $product = Product::where('type_id', $id)->select('id')->first();
        if ([] == $childType && [] == $product) {
            $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
            if (Type::destroy($id)) {
                $ret = ['state' => 'success', 'message' => '删除成功'];
            }
        }
        return \Response::json($ret);
    }

    //接口
    public function postType($type)
    {
        $ret = parent::getAllTypes($type);
        return \Response::json($ret);
    }

    //通用方法  public function
    private function getParents()
    {
        if (Cache::has('parents')) {
            $parents = Cache::get('parents');
        } else {
            $parents = Type::where('parent_id', 0)->lists('name', 'id');
            Cache::forever('parents', $parents);
        }
        return $parents;
    }
//
//    private function getAllTypes($type = 0)
//    {
//        if (0 != $type) {
//            if (Cache::has('allTypes') && Cache::has('parents')) {
//                $AllType = Cache::get('allTypes');
//            } else {
//                $parents = $this->getParents();
//                $AllType = [];
//                foreach ($parents as $key => $parent) {
//                    $AllType[$key]['name'] = $parent;
//                }
//            }
//            if (!isset($AllType[$type]['data'])) {
//                $AllType[$type]['data'] = Type::where('parent_id', $type)->lists('name', 'id');
//                Cache::forever('AllType', $AllType);
//            }
//            return $AllType[$type];
//        }
//        return false;
//    }
}